package cn.gcxy.petstore.dao.impl;

import cn.gcxy.petstore.dao.*;
import cn.gcxy.petstore.model.*;
import cn.gcxy.base.db.ConnectionHandler;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.sql.SQLException;

public class StoreDAOImpl implements IStoreDAO {
    @Override
    public boolean UpdataStore(Store store) throws  SQLException {
        PreparedStatement pre = null;
        try{
            pre = ConnectionHandler.getConnection().prepareStatement
                    ("update store set name = ?"+",balance = ?"+",password = ?"+"where id = ?");
            pre.setString(1,store.getName());
            pre.setInt(2,store.getBalance());
            pre.setString(3,store.getPassword());
            pre.setInt(4,store.getId());
            int num = pre.executeUpdate();
            if(num != 1){
                throw new SQLException();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ConnectionHandler.close(pre);
        }
        return true;
    }

    @Override
    public ArrayList<Store> FindAllStore() throws SQLException {
        ArrayList<Store> stores = new ArrayList<Store>();
        PreparedStatement pre = null;
        ResultSet res = null;
        try{
            pre = ConnectionHandler.getConnection().prepareStatement("select * from store");
            res= pre.executeQuery();
            while(res.next()){
                Store store = new Store();
                store.setId(res.getInt("id"));
                store.setName(res.getString("name"));
                store.setPassword(res.getString("password"));
                store.setBalance(res.getInt("balance"));
                stores.add(store);
            }

        }catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionHandler.close(res,pre);
        }
        return stores;
    }

    @Override
    public Store FindStoreById(int id) throws SQLException {
        Store store = null;
        PreparedStatement pre = null;
        ResultSet res = null;
        try{
            pre = ConnectionHandler.getConnection().prepareStatement
                    ("select * from store where id = ?");
            pre.setInt(1,id);
            res = pre.executeQuery();
            if (res.next()){
                store = new Store();
                store.setId(res.getInt("id"));
                store.setName(res.getString("name"));
                store.setPassword(res.getString("password"));
                store.setBalance(res.getInt("balance"));
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            ConnectionHandler.close(res,pre);
        }
        return store;
    }

}
